﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TeamArchitect.PowerTools.Ultimate.Features;

namespace YasharEl.Infrastructure.ArchitectureTools.AppModeler
{
    /// <summary>
    /// Visual Studio integration package for the feature.
    /// </summary>
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(FeaturePackage.Guid)]
    public sealed class FeaturePackage : Package
    {
        public const string Guid = "f83ae51f-e873-408a-b52e-a318b85c427b";

        [ImportMany(typeof(ILaunchPoint))]
        private IEnumerable<Lazy<ILaunchPoint, IDictionary<string, object>>> LaunchPoints { get; set; }

        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            var componentModel = this.GetService(typeof(SComponentModel)) as IComponentModel;
            componentModel.DefaultCompositionService.SatisfyImportsOnce(this);

            InitializeVsLaunchPoints();
        }

        private void InitializeVsLaunchPoints()
        {
            var menuCommandService = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (menuCommandService != null)
            {
                var featureLaunchPoints = this.LaunchPoints
                    .Select(lazy => lazy.Value)
                    .OfType<VsLaunchPoint>()
                    .Where(launchPoint => launchPoint.GetType().Assembly == this.GetType().Assembly);

                foreach (var launchPoint in featureLaunchPoints)
                {
                    menuCommandService.AddCommand(launchPoint);
                }
            }
        }
    }
}